//
//  NetworkResponse.m
//  ServiceCode
//
//  Created by 曹连华 on 2020/3/30.
//
#import "NetworkRequestResponse.h"
#import "Network.h"
#import "NetworkOperationParam.h"

@interface NetworkOperationParam ()

@property(nonatomic, copy) NSString *requestUrl;                        //请求url
@property(nonatomic, strong) NSDictionary *requestParam;                //参数

@end

@implementation NetworkRequestResponse

+ (NSDictionary *)demandParam:(NetworkOperationParam *)aParam {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    if (aParam.needSignature) {//需要签名
        NSString *timeStamp = [[NetworkConfig sharedInstance] serverTimestamp];
        NSString *signature = [[NetworkConfig sharedInstance] getSignature:aParam.requestParam];
        [dict setObject:@"md5" forKey:@"signature_method"];
        [dict setObject:timeStamp?:@"" forKey:@"timestamp"];
        [dict setObject:signature?:@"" forKey:@"signature"];
    }
    [dict setObject:[NetworkConfig sharedInstance].token?:@"" forKey:@"token"];
    [dict setObject:[NetworkConfig sharedInstance].traderName?:@"" forKey:@"trader"];
    return dict;
}
/**
 *  功能:接口调用成功处理
 */
+ (void)successWithTask:(NSURLSessionDataTask *)task
         responseObject:(id)responseObject
                  param:(NetworkOperationParam *)aParam {
    
    //数据的二次加工
    id data = [responseObject objectForKey:@"data"];
    NSString *rtnCode = [responseObject objectForKey:@"rtn_code"];
    NSString *rtn_tip = [responseObject objectForKey:@"rtn_tip"];
    NSString *rtn_msg = [responseObject objectForKey:@"rtn_msg"];
    NSString *ip = [responseObject objectForKey:@"clientIp"];
    if (ip.length > 0) {
        [NetworkConfig sharedInstance].ip = ip;
    }
    
    NSError *error = nil;
    //rtn_code不为0时，将aResponseObject作为error的userInfo传过去
    if (rtnCode.length > 0 && ![rtnCode isEqualToString:@"0"]) {
        NSString *msg = rtn_tip;
        if (!msg || [msg isEqualToString:@""]) {
            msg = rtn_msg;
        }
        msg = msg ? msg : @"";
        NSMutableDictionary *userInfo = [responseObject mutableCopy];
        userInfo[NSLocalizedDescriptionKey] = msg;
        error = [NSError errorWithDomain:NetworkInterfaceReturnErrorDomain code:kReturnCodeNotEqualToZero userInfo:[userInfo copy]];
        
        [NetworkRequestResponse failWithTask:task error:error param:aParam];
        return ;
    }
    
    if (aParam.isNeedRacRequest) {
        [aParam.subscriber sendNext:data];
        [aParam.subscriber sendCompleted];
    } else if (aParam.callbackBlock) {
        aParam.callbackBlock(data, nil);
    }
    
    //打印成功的Response
    [NetworkRequestResponse printSuccessResponseObject:responseObject param:aParam];
}
/**
 *  功能:接口调用失败处理
 */
+ (void)failWithTask:(NSURLSessionDataTask *)task
               error:(NSError *)aError
               param:(NetworkOperationParam *)aParam {
    
    if (aParam.isNeedRacRequest) {
        if (!aParam.blockSendError) {
            [aParam.subscriber sendError:aError];
        }
    } else if (aParam.callbackBlock) {
        aParam.callbackBlock(nil, aError);
    }
    
    //打印失败的日志
    [NetworkRequestResponse printFailResponseError:aError param:aParam];
    
    //接口调用失败时删除缓存
    [[NetworkURLCache sharedInstance] removeCachedResponseForRequest:[task currentRequest]];
}
/**
 *  打印成功的Response
 *
 *  responseObject
 */
+ (void)printSuccessResponseObject:(id)aResponseObject
                            param :(NetworkOperationParam *)aParam {
#ifdef DEBUG
    NSString *description = [aResponseObject description];
    
    if (description && description.length > 0) {
        PBLog(@"\n接口名%@\n接口参数%@\n接口内容%@\n\n",aParam.requestUrl,aParam.requestParam, description);
    } else {
        PBLog(@"\n接口名%@\n接口参数%@\n接口内容%@\n\n",aParam.requestUrl,aParam.requestParam, aResponseObject);
    }
#endif
}

/**
 *  打印失败的Response
 *
 *   aParam
 *   aResponseObject
 *   aError
 */
+ (void)printFailResponseError:(NSError *)aError
                         param:(NetworkOperationParam *)aParam {
#ifdef DEBUG
    NSString *errorMessage = [aError description];
    
    if (errorMessage && errorMessage.length > 0) {
        PBLog(@"\n接口名%@\n接口参数%@\n错误信息%@\n\n", aParam.requestUrl,aParam.requestParam, errorMessage);
    } else {
        PBLog(@"\n接口名%@\n接口参数%@\n错误信息%@\n\n", aParam.requestUrl,aParam.requestParam, aError);
    }
#endif
}
@end
